package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import app.Disthanitian.thaistyle.EmerMez.EditMyAccount.Runbg;
import app.Disthanitian.thaistyle.EmerMez.EditMyAccount.WebPageTask;

public class AddContactView1 extends Activity {
	   public String displayName = "", emailAddress = "", phoneNumber = "";
	   
	   Uri uriPhoto;
	   Bitmap bitmap;
	   public int length;
	  // private ContactAdapter adapter;
	   List<MemberContact> listPersons ;
      
        Button AddContact;
        ListView listView;
        //int count = 0;
        ArrayList values;
        ArrayAdapter adapter;
        static UrlEmerMez URLlink = new UrlEmerMez();
        public static final String url = URLlink.getUrladdcon();
        public static final String urlShow = URLlink.getUrlshowcon();
        public static final String urlcheckmail = URLlink.getUrlcheckmail();
        public static final String urlGETID = URLlink.getUrlgetid(); // GETID Contact
        public static final String urlAddConList = URLlink.getUrladdconlist();
        public static final String urlDeleteConList =URLlink.getUrldeleteconlist();
        public static String result = "";
        public static String result1 = "";
        String Dataname="";
        String Datanumber="";
        String Dataemail="";
        String Datapassword="";
        String cutNumber="";
        RandomPassword newclass;
        
        InputStream is = null;
        String js_result = "";
        HttpPost httppost = null;
        MemberUser user = new MemberUser();
        String userid;
        String contactid;
        String deletecontactmail;
        String deletecontactid;
        String userfirstname=user.getFirstname();
        
        MemberContact contact = new MemberContact();
        
        String IfPhone;
        String IfName;
        
        // JSON OBJECT CONTACT
       public String DataContactfirstname1 ;
       public String DataContactemail1;
       public String DataContactphonenum1;
        
        // 1.Run ShowContact
        // 2.Add ContactList
        // 3.Check Email is have Account
        // 4.If not Account is Create Account
    
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.addcontact);
                actionBar();

                listView = (ListView) findViewById(R.id.contactList);
                
                // CLICK DELETE LISTVIEW (CONTACT)
                listView.setOnItemLongClickListener(new OnItemLongClickListener() {

                        public boolean onItemLongClick(AdapterView<?> a, View v,int position, long id) {
                                DialogConfirm(); //Show Dialog
                                
                               String selectdelete =(String) a.getItemAtPosition(position);
                                
                                //values.remove(position);
                				adapter.notifyDataSetChanged();
                				adapter.notifyDataSetInvalidated();
                                
                               deletecontactmail = selectdelete.substring(selectdelete.lastIndexOf("Email:")+6);
                               Toast.makeText(AddContactView1.this, "Delete:"+deletecontactmail,Toast.LENGTH_LONG).show();
                                                               
                                return true;
                        }

                });
                
                // CALL SHOW ALL CONTACT
                WebPageTask task = new WebPageTask();
                task.execute();

        }
        
    	public void actionBar(){
    		
    		ActionBar actionBar = getActionBar();
    		actionBar.setDisplayHomeAsUpEnabled(true);
    		actionBar.setTitle("Contactlist");
    	
    		
    	}
        
        //Dialog Delete Contact
        
        public void DialogConfirm(){
                
                 AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
                 builder.setMessage("Are you sure you want to delete your contactlist?");
                 builder.setCancelable(false);
                 builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //Toast.makeText(getApplicationContext(), id,Toast.LENGTH_LONG).show();
                                // Check IDCONTACT will delete
                                RunDeleteIDCONTACT f = new RunDeleteIDCONTACT();
                                f.execute();
                                
                                RunDeleteContactList g = new RunDeleteContactList();
                                g.execute();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                 dialog.cancel();
                            }
                        });
                 AlertDialog alert = builder.create();
                 alert.show();
        }
        
        public String DeleteContactList(){
                
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("userid",userid));
                nameValuePairs.add(new BasicNameValuePair("contactid",deletecontactid));

                return postDataDeleteContactList(urlDeleteConList,nameValuePairs);
        
                
        }

        public String postDataDeleteContactList(String url,List<NameValuePair> nameValuePairs) {

                HttpClient httpclient = new DefaultHttpClient();
                httppost = new HttpPost(url);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");

                try {
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        //StringBuilder sb = new StringBuilder();

                        String line;
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        js_result = sb.toString();
                        return js_result;
                } catch (ClientProtocolException e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                } catch (IOException e) {
                }
                return null;
        }
        
        protected class RunDeleteContactList extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {
                        result =  DeleteContactList();
                        return result;
                }

                protected void onPostExecute(String result) {
                        if (result.trim().equals("ok")) {
                                Toast.makeText(AddContactView1.this, "Delete ContactList Sucsess ",Toast.LENGTH_LONG).show();
                               
                                WebPageTask task = new WebPageTask();
                                task.execute();
                             
                        }  
                }

        }
          
        
       public String CheckIDDelete() {
                
                
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("email",deletecontactmail));
        
                return postDataIDDelete(urlGETID, nameValuePairs);
        }

        private String postDataIDDelete(String url, List<NameValuePair> nameValuePairs) {
                HttpClient httpclient = new DefaultHttpClient();
                httppost = new HttpPost(url);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");

                try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        //StringBuilder sb = new StringBuilder();

                        String line;
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        js_result = sb.toString();
                        return js_result;
                } catch (ClientProtocolException e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                } catch (IOException e) {
                }
                return null;
        }
        
        
        protected class RunDeleteIDCONTACT extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {

                        result = CheckIDDelete();
                        return result;
                }

                protected void onPostExecute(String result) {

                        try {

                                JSONArray jArray = new JSONArray(result);

                                for (int i = 0; i < jArray.length(); i++) {
                                        JSONObject jo = jArray.getJSONObject(i);

                                        String id = jo.getString("user_id");
                                        deletecontactid=id;
                                      //  Toast.makeText(AddContactView1.this,"ID DELETE"+deletecontactid +""+ userid,Toast.LENGTH_LONG).show();

                                }
                        } catch (JSONException e) {
                                Log.e("log_tag", "Error parsing data " + e.toString());

                        }

                }
        }
//----------------------------------------------------------------------
        // Action Menu Bar (Plus BTN)
        public boolean onCreateOptionsMenu(Menu menu) {
                // TODO Auto-generated method stub
                MenuInflater inflater = getMenuInflater();
                inflater.inflate(R.menu.contacts, menu);

                return true;
        }
    // WHEN CLICK ADD CONTACT
        public boolean onOptionsItemSelected(MenuItem item) {
                // TODO Auto-generated method stub
                switch (item.getItemId()) {
                case R.id.action_addcontact:
                        CallContact();
                }
                return super.onOptionsItemSelected(item);
        }

        private void CallContact() {
             //   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                // BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
            //    intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
             //   startActivityForResult(intent, 1);
        	Intent intent1=new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
    		startActivityForResult(intent1,0);

        }

	// INTENT CONTACT
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//String displayName = "", emailAddress = "", phoneNumber = "";
		String id = null;
		if(requestCode==0){
         
        	// Do your stuff here...
		if (data != null) {
			Uri uri = data.getData();

			ContentResolver cr = getContentResolver();
			// ContactsContract.Contacts.CONTENT_URI
			Cursor cur = cr.query(uri, null, null, null, null);
			if (cur.getCount() > 0) {
				while (cur.moveToNext()) {
					 id = cur.getString(cur
							.getColumnIndex(ContactsContract.Contacts._ID));
					displayName = cur
							.getString(cur
									.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

					Cursor emailCur = cr.query(
							ContactsContract.CommonDataKinds.Email.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Email.CONTACT_ID
									+ " = ?", new String[] { id }, null);
					while (emailCur.moveToNext()) {
						// This would allow you get several email addresses
						// if the email addresses were stored in an array
						emailAddress = emailCur
								.getString(emailCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
						String emailType = emailCur
								.getString(emailCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
					}
					emailCur.close();

					if (Integer
							.parseInt(cur.getString(cur
									.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
						// Query phone here. Covered next
						Cursor pCur = cr
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = ?", new String[] { id },
										null);
						while (pCur.moveToNext()) {
							// Do something with phones

							phoneNumber = pCur
									.getString(pCur
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						}
						pCur.close();
					}

				}

			}
			
			 // GET Photo
            Long idphoto = Long.parseLong(id);
            byte[] data1 = null;
            Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idphoto);
            Uri photoUri=Uri.withAppendedPath(person,ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
            //photoUri
            
            Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
            InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),my_contact_Uri);            
            BufferedInputStream buf =new BufferedInputStream(photo_stream);
            Bitmap my_btmp = BitmapFactory.decodeStream(buf); //my_btmp

			if (emailAddress.isEmpty()) {
				
				contact.setContactName(displayName);
				contact.setContactPhone(phoneNumber);
				contact.setUriPhoto(photoUri);
				InputEmail();
				
				String mail = contact.getContactEmail();
				//Toast.makeText(AddContactView1.this, mail +contact.getContactName()+contact.getContactPhone(), Toast.LENGTH_LONG).show();
				
				
			} else {

				DataContact(phoneNumber, emailAddress, displayName);
				Toast.makeText(AddContactView1.this,phoneNumber + emailAddress + displayName, Toast.LENGTH_LONG).show();
			}
			
		}
		}
		
		if(resultCode == Activity.RESULT_OK && requestCode==1){
     
        	DataContact(contact.getContactPhone(), contact.getContactEmail(), contact.getContactName());   
            //AddContactView1.this.finish();
		}
	}
		
	
        
        // GET DATA FROM CONTACT INTO VARIABLE
	
    public void SendDataEmail(){
    	
    	String mail = contact.getContactEmail();
    	String name = contact.getContactName();
    	String phone = contact.getContactPhone();
    	//Toast.makeText(AddContactView1.this,phone+ mail + name, Toast.LENGTH_LONG).show();
    	//	DataContact(phone, mail, name);
       	
    }
    // GET DATA FROM CONTACT INTO VARIABLE
        public void DataContact(String number,String email, String name) {
                cutNumber = number;
                //cutNumber.replace("(", "").replace(")", "").replace("-","").replace(" ", "");
                String newNumber =cutNumber.replace("(", "").replace(")", "").replace("-","").replace(" ", "");
                
                newclass = new RandomPassword();
                newclass.getRandomString();
        
                Dataname =name;
                Datanumber =newNumber;
                Dataemail = email;
                Datapassword = newclass.getRandomString();
                // uriPhoto = uri;
           
                
                
                // CHECK CONTACT IS ACCOUNT 
                RunCheck b = new RunCheck();
                b.execute();
                
                //Runbg a = new Runbg();
                //a.execute();
        
}   
        public void InputEmail(){
        	
        	Intent newAct = new Intent(this, AddContactEmail.class);
        	startActivityForResult(newAct,1);
	       	
        }
        

        
        public String checkemail() {
                

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("email", Dataemail));

                return postDataCheck(urlcheckmail,nameValuePairs);

        }
        
        
        
        public String postDataCheck(String url,List<NameValuePair> nameValuePairs) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");
                try {
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        String line = "";
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        String page = sb.toString();
                        return page;
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                }
                return null;
        }
        
        // GETID CONTACT //
        public String ShowID() {
                
                
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("email",Dataemail));
        
                return postDataID(urlGETID, nameValuePairs);
        }

        private String postDataID(String url, List<NameValuePair> nameValuePairs) {
                HttpClient httpclient = new DefaultHttpClient();
                httppost = new HttpPost(url);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");

                try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        //StringBuilder sb = new StringBuilder();

                        String line;
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        js_result = sb.toString();
                        return js_result;
                } catch (ClientProtocolException e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                } catch (IOException e) {
                }
                return null;
        }

        public String DataSendContact(){
                
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("firstname",Dataname));
                nameValuePairs.add(new BasicNameValuePair("email",Dataemail));
                nameValuePairs.add(new BasicNameValuePair("phone",Datanumber));
                nameValuePairs.add(new BasicNameValuePair("password",Datapassword));

                return InsertData(url,nameValuePairs);
                
        }

        private String InsertData(String url, List<NameValuePair> nameValuePairs) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");
                try {
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        String line = "";
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        String page = sb.toString();
                        return page;
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                }
                return null;

        }
        
        
        public String ShowContact() {
                
                userid=user.getId(); // GET ID USER
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("userid",userid));
      
                return postData(urlShow,nameValuePairs);
        }

        public String postData(String urlShow,List<NameValuePair> nameValuePairs) {

                HttpClient httpclient = new DefaultHttpClient();
                httppost = new HttpPost(urlShow);
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer("");

                try {
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        in = new BufferedReader(new InputStreamReader(response.getEntity()
                                        .getContent()));

                        //StringBuilder sb = new StringBuilder();

                        String line;
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                                sb.append(line + NL);
                        }
                        in.close();
                        js_result = sb.toString();
                        return js_result;
                } catch (ClientProtocolException e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                } catch (IOException e) {
                }
                return null;
        }
        
        //ShowContact();
        protected class WebPageTask extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {

                        result1 = ShowContact();
                        return result1;
                }
                
                //Count JSON
                public int count = 0;
            

                protected void onPostExecute(String result1) {
                	
                                      
                	   if(result1.trim().equals("nodata")){
                		   Toast.makeText(AddContactView1.this,result1,
                				   Toast.LENGTH_LONG).show();
                		 values = new ArrayList();
                		 values.add("");
                		 adapter = new ArrayAdapter(AddContactView1.this, android.R.layout.simple_list_item_1,android.R.id.text1, values);
                		 listView.setAdapter(adapter);
                		 //  listPersons = new ArrayList<MemberContact>( length);
                          // listPersons.add(new MemberContact(DataContactfirstname1,DataContactemail1, DataContactphonenum1, uriPhoto));
                		  //  adapter = new ContactAdapter(AddContactView1.this, R.layout.listview_item_rows,listPersons);
                    		//listView.setAdapter(adapter);
                	   }else{
                		   
                        values = new ArrayList();

                        try { 
                        	 

                                JSONArray jArray = new JSONArray(result1);
                                length = jArray.length();
                                for (int i = 0; i < jArray.length(); i++) {
                                        JSONObject jo = jArray.getJSONObject(i);

                                         String firstname1 = jo.getString("firstname");
                                         String email1 = jo.getString("email");
                                         String phonenum1 = jo.getString("phonenum");
                                         
                                       //  listPersons = new ArrayList<MemberContact>( length);
                                        // listPersons.add(new MemberContact(DataContactfirstname1,DataContactemail1, DataContactphonenum1, uriPhoto));
 
                                        values.add("Name:" +firstname1 + "\n Phone:" +  phonenum1 + "\n Email:" + email1 +"\n_________________________________");

                                        adapter = new ArrayAdapter(AddContactView1.this, android.R.layout.simple_list_item_1,android.R.id.text1, values);
                                        listView.setAdapter(adapter);
                                        //loadPersons();
                                        //adapter = new ContactAdapter(AddContactView1.this, R.layout.listview_item_rows,listPersons);
                                		//listView.setAdapter(adapter);
                                		//count++;
                                		//Toast.makeText(AddContactView1.this,"Count"+ count,Toast.LENGTH_LONG).show();
                                }
                                
                                
                                //listView.setAdapter(adapter);
                                //adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                                Log.e("log_tag", "Error parsing data " + e.toString());

                        }
                	   } //--------------end 

               }
                        
                
                
                
        }
        
    	private List<MemberContact> loadPersons() {
   		 listPersons = new ArrayList<MemberContact>( length);
   		for (int i = 0; i < length; i++) {
   	   // listPersons.add(new MemberContact(displayName,emailAddress, phoneNumber, R.drawable.degaulle));
   		listPersons.add(new MemberContact(DataContactfirstname1,DataContactemail1, DataContactphonenum1, uriPhoto));
   	//	listPersons.add(new MemberContact(displayName,emailAddress, phoneNumber, bitmap));
   		}
   		return listPersons;
   	}
    
        // Send SMS
        public void sendLongSMS() {
                 
            String phoneNumber = "5556"; //Datanumber
            String message = "You are contactlist of " + userfirstname + "\n" +
                    "username : " + Dataemail + "\n" +
                        "password : " + Datapassword +"\n" +
                    "You can follow " + userfirstname + "view log of travel and security" +
                        "www.emermez.com";

            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> parts = smsManager.divideMessage(message); 
            smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null);
            
            Toast.makeText(AddContactView1.this,"Send SMS To "+Dataname+"Complete",Toast.LENGTH_LONG).show();
        }
  
        public void sendLongSMSHaveAc() {
                 
            String phoneNumber = "5556"; //Datanumber
            String message = "You are contactlist of " + userfirstname + "\n" +
                    "You can follow " + userfirstname + "view log of travel and security" + "\n"+
                        "website: www.emermez.com";

            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> parts = smsManager.divideMessage(message); 
            smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null);
            
            Toast.makeText(AddContactView1.this,"Send SMS To "+Dataname+" Complete",Toast.LENGTH_LONG).show();
        }


        protected class Runbg extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {

                        result = DataSendContact();
                        return result;
                }

                protected void onPostExecute(String result) {

                        if (result.trim().equals("ok")) {
                          //      Toast.makeText(AddContactView1.this, "Add Contact Success !!",Toast.LENGTH_LONG).show();
                                
                                
                                
                        } else if (result.trim().equals("fail")) {
                                Toast.makeText(AddContactView1.this, "Add Contact Fail !!",  Toast.LENGTH_LONG).show();
                        }

                }

        }
        
        protected class RunCheck extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {

                        result = checkemail();

                        return result;
                }

                protected void onPostExecute(String result) {
                        if (result.trim().equals("email")) {
                                Toast.makeText(AddContactView1.this, "Your Contact have Account",Toast.LENGTH_LONG).show();
                                
                                //  GET id contact
                                RunIDCONTACT c = new RunIDCONTACT();
                                c.execute();
                                
                                // INSERT CONTACTLIST
                                RunContactList d = new RunContactList();
                                d.execute();
                                
                                
                                
                        }else{
                                
                                // If NOT HAVE ACCOUNT CREATE ACCOUNT
                                Runbg a = new Runbg();
                                a.execute();
                            //  GET id contact
                                RunIDCONTACT c = new RunIDCONTACT();
                                c.execute();
                                
                                // INSERT CONTACTLIST
                                RunContactListNewAc d = new RunContactListNewAc();
                                d.execute();
                                
                                
                        }
                }
                
        }

                public String AddContactList() {
                        
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("userid",userid));
                        nameValuePairs.add(new BasicNameValuePair("contactid",contactid));

                        return postDataContactList(urlAddConList,nameValuePairs);
                
                        
                }
    
                public String postDataContactList(String url,List<NameValuePair> nameValuePairs) {

                        HttpClient httpclient = new DefaultHttpClient();
                        httppost = new HttpPost(url);
                        BufferedReader in = null;
                        StringBuffer sb = new StringBuffer("");

                        try {
                                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                HttpResponse response = httpclient.execute(httppost);
                                in = new BufferedReader(new InputStreamReader(response.getEntity()
                                                .getContent()));

                                //StringBuilder sb = new StringBuilder();

                                String line;
                                String NL = System.getProperty("line.separator");
                                while ((line = in.readLine()) != null) {
                                        sb.append(line + NL);
                                }
                                in.close();
                                js_result = sb.toString();
                                return js_result;
                        } catch (ClientProtocolException e) {
                                Log.e("log_tag", "Error converting result " + e.toString());
                        } catch (IOException e) {
                        }
                        return null;
                }
                
                protected class RunContactListNewAc extends AsyncTask<Void, Void, String> {

                        @Override
                        protected String doInBackground(Void... params) {
                                result = AddContactList();
                                return result;
                        }

                        protected void onPostExecute(String result) {
                                if (result.trim().equals("ok")) {
                                        Toast.makeText(AddContactView1.this, "Add ContactList Sucsess ",Toast.LENGTH_LONG).show();
                                        WebPageTask task = new WebPageTask();
                                        task.execute();
                                        
                                        sendLongSMS();
                                        
                                        
                                } 
                        }

                }
                
                protected class RunContactList extends AsyncTask<Void, Void, String> {

                        @Override
                        protected String doInBackground(Void... params) {
                                result = AddContactList();
                                return result;
                        }

                        protected void onPostExecute(String result) {
                                if (result.trim().equals("ok")) {
                                        Toast.makeText(AddContactView1.this, "Add ContactList Sucsess ",Toast.LENGTH_LONG).show();
                                        WebPageTask task = new WebPageTask();
                                        task.execute();
                                        
                                        sendLongSMSHaveAc();
                                        
                                        
                                } 
                        }

                }
        
        
        protected class RunIDCONTACT extends AsyncTask<Void, Void, String> {

                @Override
                protected String doInBackground(Void... params) {

                        result = ShowID();
                        return result;
                }

                protected void onPostExecute(String result) {

                        try {

                                JSONArray jArray = new JSONArray(result);

                                for (int i = 0; i < jArray.length(); i++) {
                                        JSONObject jo = jArray.getJSONObject(i);

                                        String id = jo.getString("user_id");
                                        contactid=id;

                                        
                                        //Toast.makeText(AddContactView1.this,contactid +""+ userid,Toast.LENGTH_LONG).show();

                                }
                        } catch (JSONException e) {
                                Log.e("log_tag", "Error parsing data " + e.toString());

                        }

                }
        }


}